from datetime import datetime

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from menus.models import LoginLog
from utils.JwtTool import Jwt
from .models import Staff, Deportment, Job, Rank, Role, Menus


# Create your views here.
class Login(APIView):
    # 登录
    def post(self, request):
        username = request.data.get('user')
        pwd = request.data.get('password')
        if not all([username, pwd]):
            return Response({'code': 400, 'msg': '参数错误！'})
        try:
            user = Staff.objects.get(name=username)
            if request.META.get('HTTP_X_FORWARDED_FOR'):
                ip = request.META.get('HTTP_X_FORWARDED_FOR')
            else:
                ip = request.META['REMOTE_ADDR']
            aa = request.environ.get('HTTP_USER_AGENT')
            eq = aa[aa.index('(') + 1:aa.index(')')]
            LoginLog.objects.create(login_ip=ip,equipment=eq,staff_id=user.id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '用户名不存在'})
        if user.password != pwd:
            return Response({'code': 400, 'msg': '用户名或密码错误'})
        user.last_login = datetime.now()
        user.save()
        token = Jwt().gen_jwt(user)


        return Response({
            'code': 200,
            'token': token,
            'user': user.name,
            'msg': f'欢迎{user.name}登录',
        })

    # 获取所有权限菜单
    def get(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})

        try:
            # data=user.role.menus_set.filter(menus=None)
            data = Menus.objects.filter(menu=None,role=user.role)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有权限失败'})
        _list = []
        for i in data:
            menus = []
            for j in user.role.menus_set.all():
                if j.menu_id==i.id:
                    menus.append({
                        'id': j.id,
                        'title': j.title,
                        'url': j.url
                    })
            _list.append({
                'id': str(i.id),
                'title': i.title,
                'url': i.url,
                'menu': menus,
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 修改密码
    def put(self, request):
        username = request.data.get('user')
        pwd = request.data.get('password')
        if not all([username, pwd]):
            return Response({'code': 400, 'msg': '参数错误！'})
        try:
            user = Staff.objects.get(name=username)

        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '用户名不存在'})
        user.password = pwd
        user.save()
        return Response({'code': 200, 'msg': '密码修改成功'})


class Userview(APIView):
    # 获取所有员工
    def get(self, request):
        try:
            data = Staff.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有用户失败'})
        user_list = []
        for i in data:
            user_list.append({
                'id': i.id,
                'user': i.name,
                'mobile': i.mobile,
                'email': i.email,
                'deportment': i.deportment.title,
                'job': i.job.title,
                'rank': i.rank.title,
                'role': i.role.title,
            })
        return Response({
            'code': 200,
            'msg': '获取所有用户成功',
            'data': user_list
        })

    # 添加员工
    def post(self, request):
        print(request.data)
        user = request.data.get('user')
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        email = request.data.get('email')
        deportment = request.data.get('deportment')
        job = request.data.get('job')
        rank = request.data.get('rank')
        role = request.data.get('role')

        if not all([user, password, email, deportment, job, rank, role]):
            return Response({'code': 400, 'msg': '参数错误！'})
        if Staff.objects.filter(name=user):
            return Response({'code': 400, 'msg': '用户已存在'})
        try:
            Staff.objects.create(
                name=user,
                mobile=mobile,
                password=password,
                email=email,
                deportment_id=deportment,
                job_id=job,
                rank_id=rank,
                role_id=role
            )
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '用户添加失败'})
        return Response({'code': 201, 'msg': '用户添加成功'})


class UserInfo(APIView):
    # 获取单个员工
    def get(self, request, id):
        try:
            data = Staff.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '用户信息不存在'})
        return Response({
            'code': 200,
            'msg': '获取单个用户成功',
            'data': {
                'id': data.id,
                'user': data.name,
                'email': data.email,
                'deportment': data.deportment.id,
                'job': data.job.id,
                'rank': data.rank.id,
                'role': data.role.id,
            }
        })

    # 修改员工信息
    def put(self, request, id):
        user = request.data.get('user')
        email = request.data.get('email')
        mobile = request.data.get('mobile')
        deportment = request.data.get('deportment')
        job = request.data.get('job')
        rank = request.data.get('rank')
        role = request.data.get('role')

        if not all([user, email, deportment, job, rank, role]):
            return Response({'code': 400, 'msg': '参数错误！'})

        if not Staff.objects.filter(id=id):
            return Response({'code': 400, 'msg': '用户不存在'})
        try:
            Staff.objects.filter(id=id).update(
                name=user,
                email=email,
                deportment_id=deportment,
                job_id=job,
                rank_id=rank,
                role_id=role
            )
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '用户修改失败'})
        return Response({'code': 201, 'msg': '用户修改成功'})

    # 删除员工信息
    def delete(self, request, id):
        if not Staff.objects.filter(id=id):
            return Response({'code': 400, 'msg': '用户不存在'})
        try:
            Staff.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '删除单个用户失败'})
        return Response({'code': 204, 'msg': '删除单个用户成功'})


class DepView(APIView):
    # 获取所有部门
    def get(self, request):
        try:
            data = Deportment.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有部门失败'})
        _list = []
        for i in data:
            if i.id == 1:
                user = Staff.objects.filter(deportment_id=i.id, job_id=1)
            elif i.id == 2:
                user = Staff.objects.filter(deportment_id=i.id, job_id=2)
            else:
                user = Staff.objects.filter(deportment_id=i.id, job_id=3)
            _list.append({
                'id': i.id,
                'title': i.title,
                'user': user[0].name if user else '待定'
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 添加部门
    def post(self, request):
        title = request.data.get('title')

        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if Deportment.objects.filter(title=title):
            return Response({'code': 400, 'msg': '部门已存在'})
        try:
            Deportment.objects.create(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '部门添加失败'})
        return Response({'code': 201, 'msg': '部门添加成功'})


class DepInfo(APIView):
    # 获取单个部门
    def get(self, request, id):
        try:
            data = Deportment.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '部门信息不存在'})
        return Response({
            'code': 200,
            'msg': '获取单个部门成功',
            'data': {
                'id': data.id,
                'title': data.title
            }
        })

    # 修改部门信息
    def put(self, request, id):
        title = request.data.get('title')

        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if not Deportment.objects.filter(id=id):
            return Response({'code': 400, 'msg': '部门不存在'})
        if Deportment.objects.filter(title=title):
            return Response({'code': 400, 'msg': '部门已存在'})
        try:
            Deportment.objects.filter(id=id).update(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '部门修改失败'})
        return Response({'code': 201, 'msg': '部门修改成功'})

    # 删除部门
    def delete(self, request, id):
        if not Deportment.objects.filter(id=id):
            return Response({'code': 400, 'msg': '部门不存在'})
        try:
            Deportment.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '部门删除失败'})
        return Response({'code': 204, 'msg': '部门删除成功'})


class JobView(APIView):
    # 获取所有岗位
    def get(self, request):
        try:
            data = Job.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有岗位失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'title': i.title
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 添加岗位
    def post(self, request):
        title = request.data.get('title')

        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if Job.objects.filter(title=title):
            return Response({'code': 400, 'msg': '岗位已存在'})
        try:
            Job.objects.create(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '岗位添加失败'})
        return Response({'code': 201, 'msg': '岗位添加成功'})


class JobInfo(APIView):
    # 获取单个岗位
    def get(self, request, id):
        try:
            data = Job.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '岗位信息不存在'})
        return Response({
            'code': 200,
            'msg': '获取单个岗位成功',
            'data': {
                'id': data.id,
                'title': data.title
            }
        })

    # 修改岗位信息
    def put(self, request, id):
        title = request.data.get('title')

        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if not Job.objects.filter(id=id):
            return Response({'code': 400, 'msg': '岗位不存在'})
        if Job.objects.filter(title=title):
            return Response({'code': 400, 'msg': '岗位已存在'})
        try:
            Job.objects.filter(id=id).update(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '岗位修改失败'})
        return Response({'code': 201, 'msg': '岗位修改成功'})

    # 删除部门
    def delete(self, request, id):
        if not Job.objects.filter(id=id):
            return Response({'code': 400, 'msg': '岗位不存在'})
        try:
            Job.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '岗位删除失败'})
        return Response({'code': 204, 'msg': '岗位删除成功'})


class RankView(APIView):
    # 获取所有职级
    def get(self, request):
        try:
            data = Rank.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有职级失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'title': i.title
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 添加职级
    def post(self, request):
        title = request.data.get('title')

        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if Rank.objects.filter(title=title):
            return Response({'code': 400, 'msg': '职级已存在'})
        try:
            Rank.objects.create(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '职级添加失败'})
        return Response({'code': 201, 'msg': '职级添加成功'})


class RankInfo(APIView):
    # 获取单个职级
    def get(self, request, id):
        try:
            data = Rank.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '职级信息不存在'})
        return Response({
            'code': 200,
            'msg': '获取单个职级成功',
            'data': {
                'id': data.id,
                'title': data.title
            }
        })

    # 修改职级信息
    def put(self, request, id):
        title = request.data.get('title')
        # print(title)
        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if not Rank.objects.filter(id=id):
            return Response({'code': 400, 'msg': '职级不存在'})
        if Rank.objects.filter(title=title):
            return Response({'code': 400, 'msg': '职级已存在'})
        try:
            Rank.objects.filter(id=id).update(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '职级修改失败'})
        return Response({'code': 201, 'msg': '职级修改成功'})

    # 删除职级
    def delete(self, request, id):
        if not Rank.objects.filter(id=id):
            return Response({'code': 400, 'msg': '职级不存在'})
        try:
            Rank.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '职级删除失败'})
        return Response({'code': 204, 'msg': '职级删除成功'})


class RoleView(APIView):
    # 获取所有角色
    def get(self, request):
        try:
            data = Role.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有角色失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'title': i.title
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 添加角色
    def post(self, request):
        title = request.data.get('title')

        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if Role.objects.filter(title=title):
            return Response({'code': 400, 'msg': '角色已存在'})
        try:
            Role.objects.create(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '角色添加失败'})
        return Response({'code': 201, 'msg': '角色添加成功'})


class RoleInfo(APIView):
    # 获取单个角色
    def get(self, request, id):
        try:
            data = Role.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '角色不存在'})
        return Response({
            'code': 200,
            'msg': '获取单个角色成功',
            'data': {
                'id': data.id,
                'title': data.title
            }
        })

    # 修改角色信息
    def put(self, request, id):
        title = request.data.get('title')
        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if not Role.objects.filter(id=id):
            return Response({'code': 400, 'msg': '角色不存在'})
        if Role.objects.filter(title=title):
            return Response({'code': 400, 'msg': '角色已存在'})
        try:
            Role.objects.filter(id=id).update(title=title)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '角色修改失败'})
        return Response({'code': 201, 'msg': '角色修改成功'})

    # 删除角色
    def delete(self, request, id):
        if not Role.objects.filter(id=id):
            return Response({'code': 400, 'msg': '角色不存在'})
        try:
            role = Role.objects.get(id=id)
            role.menus_set.clear()
            role.delete()

        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '角色删除失败'})
        return Response({'code': 204, 'msg': '角色删除成功'})


class PowerView(APIView):
    # 获取所有权限菜单
    def get(self, request):
        try:
            data = Menus.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有权限失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'title': i.title,
                'menu': i.menu.title if i.menu else '',
                'url': i.url,
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 添加权限菜单
    def post(self, request):
        title = request.data.get('title')
        menu = request.data.get('menu', )
        url = request.data.get('url')
        # print('------', menu, 'a')
        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if Menus.objects.filter(title=title, url=True):
            return Response({'code': 400, 'msg': '权限菜单已存在'})
        try:
            Menus.objects.create(title=title, menu_id=menu, url=url)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '权限菜单加失败'})
        return Response({'code': 201, 'msg': '权限菜单添加成功'})


class PowerInfo(APIView):
    # 获取单个权限菜单
    def get(self, request, id):
        try:
            data = Menus.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '菜单不存在'})
        return Response({
            'code': 200,
            'msg': '获取单个权限菜单成功',
            'data': {
                'id': data.id,
                'title': data.title,
                'url': data.url,
                'menu': data.menu.id if data.menu else ' ',
            }
        })

    # 修改角色权限菜单
    def put(self, request, id):
        title = request.data.get('title')
        url = request.data.get('url')
        menu_id = request.data.get('menu')

        if not title:
            return Response({'code': 400, 'msg': '参数错误'})
        if not Menus.objects.filter(id=id):
            return Response({'code': 400, 'msg': '权限菜单不存在'})
        menu = Menus.objects.filter(title=title)
        if menu and menu[0].id != id:
            return Response({'code': 400, 'msg': '权限菜单已存在'})

        try:

            menu = Menus.objects.get(id=id)
            menu.title = title
            menu.url = url
            menu.save()
            if menu_id!=' ':
                menu.menu_id = menu_id
                menu.save()

        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '权限菜单修改失败'})
        return Response({'code': 201, 'msg': '权限菜单修改成功'})

    # 删除权限菜单
    def delete(self, request, id):
        if not Menus.objects.filter(id=id):
            return Response({'code': 400, 'msg': '权限菜单不存在'})
        try:
            menu = Menus.objects.get(id=id)
            # menu.role.all()
            menu.delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '权限菜单删除失败'})
        return Response({'code': 204, 'msg': '权限菜单删除成功'})


class RolePower(APIView):
    # 获取当前用户权限
    def get(self, request, id):
        try:
            role = Role.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '角色不存在'})
        _list = []
        for i in role.menus_set.all():
            _list.append(i.id)
        return Response({
            'code': 200,
            'msg': '角色权限获取成功',
            'data': _list
        })

    # 修改角色权限
    def put(self, request, id):
        ids = request.data.get('ids')
        direction = request.data.get('direction')
        print(ids, direction)
        try:
            role = Role.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '角色不存在'})
        menus = Menus.objects.filter(id__in=ids)
        if direction == 'right':
            role.menus_set.add(*menus)

        else:
            role.menus_set.remove(*menus)
        return Response({'code': 201, 'msg': '权限修改成功'})
